import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/course/course_detail/course_detail_page.dart';
import 'package:edu/pages/course/course_detail/course_detail_page_logic.dart';
import 'package:edu/pages/course/course_list/course_list_page.dart';
import 'package:edu/pages/course/course_list/course_list_page_logic.dart';
import 'package:edu/pages/course/course_review/course_review_page.dart';
import 'package:edu/pages/course/course_review/course_review_page_logic.dart';
import 'package:edu/pages/course/course_review_reply/course_review_reply_page.dart';
import 'package:edu/pages/course/course_review_reply/course_review_reply_page_logic.dart';
import 'package:edu/pages/course/course_search/course_search_page.dart';
import 'package:edu/pages/course/course_search/course_search_page_logic.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_page.dart';
import 'package:edu/pages/main_tab/edu/edu_course/edu_course_page_logic.dart';
import 'package:edu/pages/main_tab/main_tab.dart';
import 'package:edu/pages/main_tab/main_tab_logic.dart';
import 'package:edu/pages/profile/account_profile_setting/account_profile_setting_page.dart';
import 'package:edu/pages/profile/account_profile_setting/account_profile_setting_page_logic.dart';
import 'package:edu/pages/profile/introduction_setting/introduction_setting_page.dart';
import 'package:edu/pages/profile/introduction_setting/introduction_setting_page_logic.dart';
import 'package:edu/pages/profile/location_setting/location_setting_page.dart';
import 'package:edu/pages/profile/location_setting/location_setting_page_logic.dart';
import 'package:edu/pages/profile/nickname_setting/nickname_setting_page.dart';
import 'package:edu/pages/profile/nickname_setting/nickname_setting_page_logic.dart';
import 'package:edu/pages/profile/profession_setting/profession_setting_page.dart';
import 'package:edu/pages/profile/profession_setting/profession_setting_page_logic.dart';
import 'package:edu/pages/profile/security/account_cancellation/account_cancellation_page.dart';
import 'package:edu/pages/profile/security/credentail_setting/credential_setting_page.dart';
import 'package:edu/pages/profile/security/credentail_setting/credential_setting_page_logic.dart';
import 'package:edu/pages/profile/security/forgot_password_setting/forgot_password_setting_page.dart';
import 'package:edu/pages/profile/security/forgot_password_setting/forgot_password_setting_page_logic.dart';
import 'package:edu/pages/profile/security/identity_verification/identity_verification_page.dart';
import 'package:edu/pages/profile/security/password_setting/password_setting_page.dart';
import 'package:edu/pages/profile/security/password_setting/password_setting_page_logic.dart';
import 'package:edu/pages/profile/security/security_setting/security_setting_page.dart';
import 'package:edu/pages/profile/security/security_setting/security_setting_page_logic.dart';
import 'package:edu/pages/profile/security/third_auth_account/third_auth_account_page.dart';
import 'package:edu/pages/signin/login/login_page.dart';
import 'package:edu/pages/signin/login/login_page_logic.dart';
import 'package:edu/pages/signin/verify_code_submit/verify_code_submit_page.dart';
import 'package:edu/pages/signin/verify_code_submit/verify_code_submit_page_logic.dart';
import 'package:edu/pages/signin/web_view/web_view_page.dart';
import 'package:edu/pages/supplement/%20shopping_cart/shopping_cart_page.dart';
import 'package:edu/pages/supplement/%20shopping_cart/shopping_cart_page_logic.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

/* 路由 */
class AppRouter {
  static const kMainTab = 'main_tab';
  // 登录注册部分
  static const kLogin = 'login';
  static const kWebViewPage = 'web_view_page';
  static const kVerifyCodeSubmit = 'verify_code_submit';
  // 个人信息部分
  static const kAccountProfileSetting = 'account_profile_setting'; // 修改个人资料
  static const kAvatarSetting = 'avatar_setting'; // 修改头像
  static const kNicknameSetting = 'nick_name_setting'; // 修改昵称
  static const kProfessionSetting = 'profession_setting'; // 修改职业
  static const kLocationSetting = 'location_setting'; // 修改地区
  static const kIntroductionSetting = 'introduction_setting'; // 修改签名
  static const kSecuritySetting = 'security_setting'; // 账号与安全
  static const kCredentialSetting = 'credentail_setting'; //修改手机号和邮箱
  static const kThirdAuthAccount = 'third_auth_account'; // 三方授权
  static const kForgotPasswordSetting =
      'forgot_password_setting'; //忘记密码/找回密码/重置密码
  static const kPasswordSetting = 'password_setting'; // 密码设置
  static const kAccountCancellation = 'account_cancellation'; // 账号注销
  static const kIdentityVerification = 'identity_verification'; // 实名认证
  static const kCourseList = 'course_list'; // 课程列表
  static const kCourseDetail = 'course_detail'; // 课程详情
  static const kCourseSearch = 'course_search'; // 课程搜索
  static const kCourseReview = 'course_review'; // 课程评价
  static const kCourseReviewReply = 'course_review_reply'; // 课程评价回复
  static const kEduCourse = 'edu_course'; // 课程学习
  static const kShoppingCart = 'shopping_cart'; // 购物车

  late final ValueNotifier<int> _routerNotifier;
  static final shared = AppRouter._();
  AppRouter._() {
    _routerNotifier = ValueNotifier(0);
  }

  void refreshRoute() {
    _routerNotifier.value++;
  }

  /*
   * 使用GoRouter(Flutter 的路由管理库）创建路由实例的配置
   */
  // 构建路由
  late final router = GoRouter(
    debugLogDiagnostics: kDebugMode,
    refreshListenable: _routerNotifier,
    initialLocation: '/$kMainTab',
    redirect: redirect,
    routes: [
      _mainTab, // 账号主页
      _login, // 登录
      _webViewPage, // 登录注册
      _VerifyCodeSubmit, // 验证码提交
      _forgotPasswordSetting, // 忘记密码/找回密码/重置密码
    ],
    errorBuilder: (context, state) {
      return const Scaffold(
        body: Center(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Text(AppStrings.needNetwork, style: TextStyle(fontSize: 20)),
          ),
        ),
      );
    },
  );

  /*
   * 账号主页的相关路由
   */
  late final _mainTab = GoRoute(
    // 路由名称
    name: kMainTab,
    // 路由路径
    path: '/$kMainTab',
    // 构建页面
    builder: (context, state) {
      final mainTabLogic = MainTabLogic(mainTabIndex: 3);
      return ChangeNotifierProvider(
        create: (context) => mainTabLogic,
        child: const MainTab(),
      );
    },
    // 子路由
    routes: [
      _accountProfileSetting,
      _courseList,
      _searchCourse,
      _courseDetail,
      _courseReview,
      _courseReviewReply,
      _eduCourse,
      _shoppingCart,
    ],
  );

  /*
   * 判断是否登录
   */

  /*
   * 个人资料
   */
  late final _accountProfileSetting = GoRoute(
    name: kAccountProfileSetting,
    path: kAccountProfileSetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => AccountProfileSettingPageLogic(),
        builder: (context, child) {
          return const AccountProfileSettingPage();
        },
      );
    },
    routes: [
      _nicknameSetting, // 修改昵称
      _professionSetting, // 修改职业
      _locationSetting, // 修改地区
      _introductionSetting, // 修改签名
      _securitySetting, // 账号与安全
    ],
  );

  /*
   * 修改昵称
   */
  late final _nicknameSetting = GoRoute(
    name: kNicknameSetting,
    path: kNicknameSetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => NicknameSettingPageLogic(),
        builder: (context, child) {
          return const NicknameSettingPage();
        },
      );
    },
  );

  /*
   * 修改职业
   */
  late final _professionSetting = GoRoute(
    name: kProfessionSetting,
    path: kProfessionSetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => ProfessionSettingPageLogic(),
        builder: (context, child) {
          return const ProfessionSettingPage();
        },
      );
    },
  );

  /*
   * 修改地区
   */
  late final _locationSetting = GoRoute(
    name: kLocationSetting,
    path: kLocationSetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => LocationSettingPageLogic(
          code: state.uri.queryParameters['code'],
          level: int.tryParse(state.uri.queryParameters['level'] ?? '') ?? 0,
          title: state.uri.queryParameters['title'],
        ),
        builder: (context, child) {
          return const LocationSettingPage();
        },
      );
    },
  );

  /*
   * 修改签名
   */
  late final _introductionSetting = GoRoute(
    name: kIntroductionSetting,
    path: kIntroductionSetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => IntroductionSettingPageLogic(),
        builder: (context, child) {
          return const IntroductionSettingPage();
        },
      );
    },
  );

  /*
   * 登录
   */
  late final _login = GoRoute(
    name: kLogin,
    path: '/$kLogin',
    pageBuilder: (context, state) => CustomTransitionPage(
      key: state.pageKey,
      child: ChangeNotifierProvider(
        create: (context) => LoginPageLogic(),
        child: const LoginPage(),
      ),
      // 自定义路由动画 从下往上
      transitionsBuilder: (context, animation, secondaryAnimation, child) {
        final tween = Tween<Offset>(
          begin: const Offset(0, 1),
          end: Offset.zero,
        );

        // 使用动画
        final offsetAnimation = animation.drive(tween);
        return SlideTransition(position: offsetAnimation, child: child);
      },
    ),
  );

  /*
   * WebView
   */
  late final _webViewPage = GoRoute(
    name: kWebViewPage,
    path: '/$kWebViewPage',
    builder: (context, state) {
      final page = state.uri.queryParameters['page']!;
      final title = state.uri.queryParameters['title']!;
      final bg = state.uri.queryParameters['bg']!;
      final fg = state.uri.queryParameters['fg']!;
      return WebViewPage(
        title: title,
        page: page,
        backgroundColor: bg,
        foregroundColor: fg,
      );
    },
  );

  /*
   * 验证码提交
   */
  // ignore: non_constant_identifier_names
  late final _VerifyCodeSubmit = GoRoute(
    name: kVerifyCodeSubmit,
    path: '/$kVerifyCodeSubmit',
    builder: (context, state) {
      final submitType = state.uri.queryParameters['submit_type'] ?? '';
      final holdValue = state.uri.queryParameters['hold_value'] ?? '';
      final prevRoute = state.uri.queryParameters['prev_route'] ?? '';

      return ChangeNotifierProvider(
        create: (context) => VerifyCodeSubmitPageLogic(
          submitType: submitType,
          holdValue: holdValue,
          prevRoute: prevRoute,
        ),
        builder: (context, child) {
          return const VerifyCodeSubmitPage();
        },
      );
    },
  );

  //=======================账号与安全的相关路由======================================

  /*
   * 账号与安全
   */
  late final _securitySetting = GoRoute(
    name: kSecuritySetting,
    path: kSecuritySetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => SecuritySettingPageLogic(),
        builder: (context, child) {
          return const SecuritySettingPage();
        },
      );
    },
    routes: [
      _credentialSetting, // 修改手机号和邮箱
      _thirdAuthAccount, // 第三方账号
      _passwordSetting, // 密码设置
      _identityVerification, // 身份验证
      _accountCancellation, // 账号注销
    ],
  );

  /*
   * 修改手机号和邮箱
   */
  late final _credentialSetting = GoRoute(
    name: kCredentialSetting,
    path: kCredentialSetting,
    builder: (context, state) {
      final credentialType = state.uri.queryParameters['credential_type'] ?? '';
      return ChangeNotifierProvider(
        create: (context) =>
            CredentialSettingPageLogic(credentialType: credentialType),
        builder: (context, child) {
          return const CredentialSettingPage();
        },
      );
    },
  );

  /*
   * 第三方账号
   */
  late final _thirdAuthAccount = GoRoute(
    name: kThirdAuthAccount,
    path: kThirdAuthAccount,
    builder: (context, state) {
      return const ThirdAuthAccountPage();
    },
  );

  /*
   * 忘记密码/找回密码/重置密码
   */
  late final _forgotPasswordSetting = GoRoute(
    name: kForgotPasswordSetting,
    path: '/$kForgotPasswordSetting',
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => ForgotPasswordSettingPageLogic(
          prevRoute: state.uri.queryParameters['prev_route'] ?? '',
        ),
        builder: (context, child) {
          return const ForgotPasswordSettingPage();
        },
      );
    },
  );

  /*
   * 使用旧密码修改密码
   */
  late final _passwordSetting = GoRoute(
    name: kPasswordSetting,
    path: kPasswordSetting,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => PasswordSettingPageLogic(),
        builder: (context, child) {
          return const PasswordSettingPage();
        },
      );
    },
  );

  /*
   * 实名认证
   */
  late final _identityVerification = GoRoute(
    name: kIdentityVerification,
    path: kIdentityVerification,
    builder: (context, state) {
      return const IdentityVerificationPage();
    },
  );

  /*
   * 账号注销
   */
  late final _accountCancellation = GoRoute(
    name: kAccountCancellation,
    path: kAccountCancellation,
    builder: (context, state) {
      return const AccountCancellationPage();
    },
  );

  //=======================课程的相关路由======================================

  /*
   * 课程列表
   */
  late final _courseList = GoRoute(
    name: kCourseList,
    path: kCourseList,
    builder: (context, state) {
      final categoryId = int.tryParse(
        state.uri.queryParameters['categoryId'] ?? '',
      );
      final title = state.uri.queryParameters['title'];
      return ChangeNotifierProvider(
        create: (context) =>
            CourseListPageLogic(categoryId: categoryId, title: title),
        child: const CourseListPage(),
      );
    },
  );

  /*
   * 根据输入的keyword关键字课程查询
   */
  late final _searchCourse = GoRoute(
    name: kCourseSearch,
    path: kCourseSearch,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => CourseSearchPageLogic(),
        child: const CourseSearchPage(),
      );
    },
  );

  /*
   * 课程详情
   */
  late final _courseDetail = GoRoute(
    name: kCourseDetail,
    path: kCourseDetail,
    builder: (context, state) {
      final courseId = int.tryParse(state.uri.queryParameters['id']!)!;
      return ChangeNotifierProvider(
        create: (context) => CourseDetailPageLogic(id: courseId),
        child: const CourseDetailPage(),
      );
    },
  );

  /*
   * 课程评价
   */
  late final _courseReview = GoRoute(
    name: kCourseReview,
    path: kCourseReview,
    pageBuilder: (context, state) {
      final courseId = int.tryParse(state.uri.queryParameters['course_id']!)!;
      final rating = int.tryParse(state.uri.queryParameters['rating']!)!;
      final reviewContent = state.uri.queryParameters['review_content'];
      final widget = ChangeNotifierProvider(
        create: (context) => CourseReviewPageLogic(
          courseId: courseId,
          rating: rating,
          reviewContent: reviewContent,
        ),
        child: const CourseReviewPage(),
      );

      return CustomTransitionPage(
        key: state.pageKey,
        name: state.name,
        child: widget,
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          final tween = Tween<Offset>(
            begin: const Offset(0, 1),
            end: Offset.zero,
          );
          final offestAnimation = animation.drive(tween);
          return SlideTransition(position: offestAnimation, child: child);
        },
      );
    },
  );

  /*
   * 课程评价回复
   */
  late final _courseReviewReply = GoRoute(
    name: kCourseReviewReply,
    path: kCourseReviewReply,
    pageBuilder: (context, state) {
      final reviewId = int.tryParse(state.uri.queryParameters['id']!)!;
      final courseId = int.tryParse(state.uri.queryParameters['course_id']!)!;
      final reviewRating = int.tryParse(state.uri.queryParameters['rating']!)!;
      final reviewUser = state.uri.queryParameters['user']!;
      final reviewContent = state.uri.queryParameters['content']!;
      final replyId = int.tryParse(state.uri.queryParameters['reply_id'] ?? '');
      final replyContent = state.uri.queryParameters['reply_content'];
      final widget = ChangeNotifierProvider(
        create: (context) => CourseReviewReplyPageLogic(
          reviewId: reviewId,
          courseId: courseId,
          ratting: reviewRating,
          reviewUser: reviewUser,
          reviewContent: reviewContent,
          replyId: replyId,
          replyContent: replyContent,
        ),
        child: const CourseReviewReplyPage(),
      );

      return CustomTransitionPage(
        key: state.pageKey,
        name: state.name,
        child: widget,
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          final tween = Tween<Offset>(
            begin: const Offset(0, 1),
            end: Offset.zero,
          );
          final offestAnimation = animation.drive(tween);
          return SlideTransition(position: offestAnimation, child: child);
        },
      );
    },
  );

  /*
   * 课程学习
   */
  late final _eduCourse = GoRoute(
    name: kEduCourse,
    path: kEduCourse,
    builder: (context, state) {
      final courseId = int.tryParse(state.uri.queryParameters['id']!)!;
      return ChangeNotifierProvider(
        create: (context) => EduCoursePageLogic(id: courseId),
        child: const EduCoursePage(),
      );
    },
  );

  //==============================购物车相关路由==================================
  /*
   * 购物车
   */
  late final _shoppingCart = GoRoute(
    name: kShoppingCart,
    path: kShoppingCart,
    builder: (context, state) {
      return ChangeNotifierProvider(
        create: (context) => ShoppingCartPageLogic(),
        child: const ShoppingCartPage(),
      );
    },
  );

  String? redirect(BuildContext context, GoRouterState state) {
    return null;
  }
}
